package com.wangpu.oa.web.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wangpu.oa.dto.JSONResponse;
import com.wangpu.oa.dto.UserContext;
import com.wangpu.oa.exception.OAException;
import com.wangpu.oa.service.UserService;
import com.wangpu.oa.service.impl.UserServiceImpl;
import com.wangpu.oa.util.JSONUtil;

@WebServlet("/public-api/user/login")
public class LoginServlet extends HttpServlet{
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONResponse result=new JSONResponse();
		try {
			//1.获取参数
			String account = req.getParameter("account");
			String password= req.getParameter("password");
			String captchaInput=req.getParameter("captcha");
			String loginIp=req.getRemoteHost();
			Object captcha=req.getSession().getAttribute("captcha");
			System.out.println(captcha);
			if(captcha!=null) {
				if(!captcha.equals(captchaInput)) {
					throw new IOException("验证码错误,请重试");
				}
			}
			
			//2.调用业务方法
			UserService userService=new UserServiceImpl();
			UserContext uc=userService.login(account,password,loginIp);
			//3把当前登录用户上下文放入session中
			HttpSession session=req.getSession(false);
			if(session!=null) {
				//说明之前访问过
				session.invalidate();
			}
			session=req.getSession(true);
			//System.out.println(session);
			session.setAttribute("CURRENT-USER", uc);
			session.setAttribute("LOGIN", true);
			
			//4 返回结果
			result.setCode("ok");
			result.setData(uc);
		} catch (OAException e) {
			result.setCode("0001");
			result.setMessage(e.getMessage());
		} catch (Exception e) {
			result.setCode("error");
			result.setMessage("系统繁忙，请稍候再试!");
			//打印异常信息，用于调试
			e.printStackTrace();
		} finally {
			Writer out=resp.getWriter();
			out.write(JSONUtil.toJsonString(result));
			out.close();
		}
		
	}
}